package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 因为Category在删除时，可能关联其他信息，应该进行判断
     * @param id 分类id
     */
    @Override
    public void remove(Long id) {
        /*
            // 1.添加查询条件，根据分类id查询菜品数据
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
            //2.如果已经关联，抛出一个业务异常
            if (dishService.count(dishLambdaQueryWrapper) > 0) {
                throw new CustomException("当前分类下关联了菜品，不能删除"); //已经关联菜品，抛出一个业务异常
            }

            // 1.添加查询条件，根据分类id查询菜品数据
            LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
            //2.如果已经关联，抛出一个业务异常
            if (setmealService.count(setmealLambdaQueryWrapper) > 0) {
                throw new CustomException("当前分类下关联了套餐，不能删除"); //已经关联套餐，抛出一个业务异常
            }
        */

        // 简化代码
        // 1. 判断是否关联了菜品
        if (dishService.count( new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, id)) > 0) {
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        // 简化代码
        // 2. 判断是否关联了套餐
        if (setmealService.count( new LambdaQueryWrapper<Setmeal>().eq(Setmeal::getCategoryId, id)) > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }

        //正常删除分类
        super.removeById(id);
    }
}


